package com.dong.c10_netty_chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2021-03-09 00:39
 */
public class GroupChatServerHandler  extends SimpleChannelInboundHandler<String> {

    private static Map<String,Channel> map = new HashMap<>(8);
    /**
     * 定义一个channel组, 管理所有的channel
     * 全局事件执行器  : 单例
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public GroupChatServerHandler() {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel myChannel = ctx.channel();
        String addr = ctx.channel().remoteAddress().toString()+"";
        String totalMsg = addr + "says: " + msg;
        System.out.println(totalMsg);
        channelGroup.writeAndFlush(totalMsg+"\n", channel -> !channel.equals(myChannel));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        String msg = ctx.channel().remoteAddress().toString()+"";
     //   System.out.println(msg+" 上线了");
        channelGroup.writeAndFlush("加入聊天...: "+msg);
        channelGroup.add(ctx.channel());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = ctx.channel().remoteAddress().toString()+"";
        System.out.println(msg+" 上线了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String msg = ctx.channel().remoteAddress().toString();
     //   channelGroup.writeAndFlush("用户下线了: "+msg);
        System.out.println(msg+" 离线了...");
    }

    /**
     * 自动会进行  channel 的移除
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        String msg = ctx.channel().remoteAddress().toString()+"";
        channelGroup.writeAndFlush("用户下线了: "+msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        ctx.close();
    }
}
